import { getItineraryInfoByIdForUser,//我的行程详情
  getItineraryCompanionList,//用户列表
  ItineraryCompanionAddForUser,//添加用户
  ItineraryCompanionDeleteForUser,//删除用户
  getItineraryPackingListCategoryListAllForComboBox,//分类列表
  getItineraryPackingListListAllToTreeForUser,//用戶行程行李清單列表
  ItineraryPackingListAddForUser,//添加用戶行程行李清單列表
  ItineraryPackingListDeleteForUser,//删除用戶行程行李清單列表
  postUserItineraryPackingListModifyForUser,//編輯用戶行李清單
  
 } from '../../api/home'
import { imageURL } from '../../../utils/request'


Page({
  data: {
    imageURL:'',
    itinerary_id:'',
    itineraryDetail:{},
    addImg:'',
    longitude: 116.404,  // 默認北京中心坐標
    latitude: 39.915,
    markers: [{
      id: 1,
      longitude: 116.404,
      latitude: 39.915,
      iconPath: '',
      width: 30,
      height: 40,
      title: '天安門',
      address: '北京市東城區長安街'
    }],
    selectedMarker: null,
    tabs: [],  
    tabsIndex:'', 
    visible: false,
    actionShow:false,
    currentId: null,      // 當前點擊的分類id
    userList: [],
    packingList: [
    ],
    hours: Array.from({ length: 24 }, (_, i) => (i < 10 ? '0' + i : '' + i)),
    minutes: Array.from({ length: 60 }, (_, i) => (i < 10 ? '0' + i : '' + i)),
    //添加彈框
    timeAddPopup:false,//时间添加
    showSelectPopup: false,//選擇類別
    showAddPopup:false, //添加物品
    showAddMember:false,//添加成員
    newFolderName: '',
    selectedFolder: '',
    itinerary_packing_list_category_id:'',//分類id
    itinerary_companion_id:'',//用戶id
    folderList: [], // 模擬的收藏夾
    userImg: '',
    totalChildCount:'',//合计物品数量
    totalCheckedCount:'',//已选择物品数量
    listModal:false,
    listName:'',
    itinerary_packing_list_id:''
  },
  async onLoad(e){
    const res= await getItineraryInfoByIdForUser({
      itinerary_id:e.itinerary_id
    })
    const tabs = [{ label: '總', progress: 0 }];
    const numberDay = res.data.info.number_day || 0;
    for (let i = 1; i <= numberDay; i++) {
      tabs.push({ label: String(i), progress: 0 });
    }
    // 给 list_item 每一项加 open:true
    const list_item = (res.data.list_item || []).map(item => ({
      ...item,
      open: true
    }))

    this.setData({
      itineraryDetail: {
        ...res.data,
        list_item
      },
      itinerary_id:e.itinerary_id,
      tabs,
      imageURL
    })
    this.getUserList()
    this.getTypeList()
  },
  async userClick(e){
    const id = e.currentTarget.dataset.id;

    this.setData({
      itinerary_companion_id:id,
    })
    this.getPackingList()
  },
  // 行李分类列表
  async getTypeList(){
    const res = await getItineraryPackingListCategoryListAllForComboBox()
    this.setData({
      folderList:res.data.list
    })
  },
  // 行李选择列表
async getPackingList() {
  const res = await getItineraryPackingListListAllToTreeForUser({
    itinerary_id: this.data.itineraryDetail.info.itinerary_id,
    itinerary_companion_id: this.data.itinerary_companion_id
  });

  const list = (res.data.list || []).map(item => {
    const children = item.child || [];
    const checkedCount = children.filter(c => c.status === 1).length; // ✅ 每组勾选数量

    return {
      ...item,
      open: true,
      checkedCount // ✅ 加入该字段
    };
  });

  // ✅ 计算总数
  let totalChildCount = 0;   // 所有 child 数量
  let totalCheckedCount = 0; // status === 1 的数量

  list.forEach(item => {
    const children = item.child || [];
    totalChildCount += children.length;
    totalCheckedCount += children.filter(c => c.status === 1).length;
  });

  this.setData({
    packingList: list,
    totalChildCount,
    totalCheckedCount
  });
},

  // 刪除
  async dell(){
   const res = await ItineraryCompanionDeleteForUser({
    itinerary_id:'3',
    itinerary_companion_id:'6',
   })
  },
  async confirmDelete(){
    const res = await ItineraryPackingListDeleteForUser({
      itinerary_id:this.data.itineraryDetail.info.itinerary_id,
      itinerary_packing_list_id:this.data.itinerary_packing_list_id
    })
    this.setData({
      listModal:false
    })
    if(res.data.ret==1){
      wx.showToast({  
        title: '刪除成功',
      })
      this.getPackingList()
    }
    
  },
  // 獲取朋友列表
  async getUserList(){
    const res= await getItineraryCompanionList({
      itinerary_id:this.data.itineraryDetail.info.itinerary_id,
      
    })
    this.setData({
      userList : res.data.list,
      itinerary_companion_id:res.data.list[0]?.itinerary_companion_id,
    })
  },
  onStartTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({ startTime: [hour, minute] });
    console.log('開始時間：', hour + ':' + minute);
  },

  onEndTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({ endTime: [hour, minute] });
    console.log('結束時間：', hour + ':' + minute);
  },
  addTimeClick(){
    this.setData({
      timeAddPopup:false
    })
  },
  openTimeClick(){
    this.setData({
      timeAddPopup:true
    })
  },
  toggleDay(e) {
    const index = e.currentTarget.dataset.index;
    const days = this.data.itineraryDetail.list_item;
    days[index].open = !days[index].open;
    this.setData({ 
      'itineraryDetail.list_item':days
     });
  },
  addClick(){
    wx.showToast({
      title: '添加成功',
    })
  },
  onAddTab() {
    const { tabs } = this.data;
    const newTab = { label: tabs.length, progress: 0 };
    tabs.push(newTab);
    this.setData({
      tabs
    })
  },

  onTabClick(e) {
    const index = e.currentTarget.dataset.index;
    const tab = this.data.tabs[index]
    this.setData({
      tabsIndex:index,
      scrollTarget: `day-${tab.label}` // ✅ 对应 day_num
    })
  },

  onPreviewImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.carouselImages[index],
      urls: this.data.carouselImages
    });
  },
  // 地圖區域變化
  onRegionChange(e) {
    console.log('地圖移動', e);
  },

  // 回到當前位置
  moveToLocation() {
    wx.navigateTo({
      url: `/pages/Itinerary/bigMap/bigMap?itinerary_id=${this.data.itinerary_id}&type=my`,
    })
  },

  editClick(){
    wx.navigateTo({
      url: `/pages/Itinerary/routeDetailsEdit/routeDetailsEdit?itinerary_id=${this.data.itineraryDetail.info.itinerary_id}`,
    })
  },
  goAccount(){
    wx.navigateTo({
      url: `/pages/transaction/bill/bill?itinerary_id=${this.data.itineraryDetail.info.itinerary_id}`,
    })
  },
  
  itemShowClick(){
    this.setData({ showAddPopup: true });
  },
  memberClick(){
    this.setData({ showAddMember: true });
  },
  // 輸入新收藏夾名稱
  onInputFolderName(e) {
    this.setData({ newFolderName: e.detail.value });
  },

  // 打開選擇收藏夾 
  openSelectPopup() {
    this.setData({ showSelectPopup: true });
  },

  // 關閉選擇收藏夾
  closeSelectPopup() {
    this.setData({ showSelectPopup: false });
  },

  // 選擇收藏夾
  chooseFolder(e) {
    this.setData({
      selectedFolder: e.currentTarget.dataset.name,
      itinerary_packing_list_category_id: e.currentTarget.dataset.id,
      showSelectPopup: false
    });
  },

  // 關閉添加收藏彈框
  closePopup() {
    this.setData({ 
      showAddPopup: false,
      showAddMember:false ,
      timeAddPopup:false,
      listModal:false
     });
  },
  imageClick() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'], // 只選圖片
      sourceType: ['album', 'camera'], // 相冊/拍照
      sizeType: ['compressed'], // 壓縮圖，減少體積
      success:async (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        console.log(res);
        wx.uploadFile({
          url: 'https://bee.teamotto.cn/api/Upload/uploadFile', // 替换为你的服务器上传接口地址
          filePath: tempFilePath, // 选中的图片或视频的临时文件路径
          name: 'file', // 服务器端接收文件的字段名
          formData: {
            // 其他需要传递给服务器的数据
          },
          success:(uploadRes) =>{
            console.log(JSON.parse(uploadRes.data).data.path); // 服务器返回的数据
            this.setData({
              addImg : JSON.parse(uploadRes.data).data.path
            })
          }
        });
        this.setData({
          userImg:tempFilePath
        })
      }
    });
  },
  // 確認添加類別
  async confirmAdd() {
    const { newFolderName, selectedFolder } = this.data;
    if (!newFolderName || !selectedFolder) {
      wx.showToast({ title: '請完整填寫需要添加的物品', icon: 'none' });
      return;
    }
    // 添加
    await ItineraryPackingListAddForUser({
      itinerary_id:this.data.itineraryDetail.info.itinerary_id,
      itinerary_companion_id:this.data.itinerary_companion_id,
      itinerary_packing_list_category_id:this.data.itinerary_packing_list_category_id,
      name:this.data.newFolderName,
    })
    this.getPackingList()
  
    this.setData({

      newFolderName: '',
      selectedFolder: '',
    })
    // this.triggerEvent('confirm', {
    //   folder: newFolderName || selectedFolder
    // });
    this.closePopup();
  },
  // 確認添加成員
  async confirmAddUser() {
    const res = await ItineraryCompanionAddForUser({
      itinerary_id:this.data.itineraryDetail.info.itinerary_id,
      avatar_url:this.data.addImg,
      name:this.data.newFolderName
    })
    wx.showToast({
      title: '添加成功',
    })
    this.getUserList()
    this.setData({
      userImg:'',
      newFolderName:''
    })
    this.closePopup();
  },
  noop() {},

  toggleCategory(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({
      packingList: this.data.packingList.map(cat =>
        cat.itinerary_packing_list_category_id === id ? { ...cat, open: !cat.open } : cat
      )
    });
  },

  async toggleItem(e) {
    const cid = e.currentTarget.dataset.cid;    // 外層分類id
    const index = e.currentTarget.dataset.index; // 子項下標
  
    // 找到分类
    const category = this.data.packingList.find(
      cat => cat.itinerary_packing_list_category_id === cid
    );
    if (!category) return;
  
    // 找到子项
    const item = category.child[index];
    if (!item) return;
    let totalCheckedCount = this.data.totalCheckedCount
    // 翻转 status
    const newStatus = item.status === 1 ? 0 : 1;      
    if(newStatus==0){
      this.setData({
        listModal:true,
        listName:item.name,
        itinerary_packing_list_id:item.itinerary_packing_list_id
      })
    }
    try {
      // 调用接口
      await postUserItineraryPackingListModifyForUser({
        itinerary_id: this.data.itineraryDetail.info.itinerary_id,
        itinerary_packing_list_id: item.itinerary_packing_list_id,
        status: newStatus
      });
  
      // 更新本地数据
      this.setData({
        packingList: this.data.packingList.map(cat => {
          if (cat.itinerary_packing_list_category_id === cid) {
            const child = [...cat.child];
            child[index].status = newStatus;
            return { ...cat, child };
          }
          return cat;
        }),
      });
      console.log('更新後:', this.data.packingList);
      this.getPackingList()
  
    } catch (err) {
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
      console.error('修改失败:', err);
    }
  },
   
  
  // 打開操作彈框
  actionClick(e) {
    this.setData({
      currentId: e.currentTarget.dataset.id,
      actionShow: true
    });
  },
  openVisible(){
    this.getPackingList()
    this.setData({
      visible:true
    })
  },
  // 完成
  baggageOk(){
    this.setData({
      visible:false
    })
  },
  itemOk(){
    this.setData({
      itemVisible:false
    })
  },
  // 添加物品
  baggageAdd(){
    this.setData({
      visible:false,
      itemVisible:true
    })
  },
  handleAction(){
    this.setData({
      actionShow:false
    })
  },
  
});
